package cn.lyf.myblog.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.*;

import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.Service;

import static cn.lyf.myblog.controller.api.JsonUtils.*;

import java.util.List;
import java.util.stream.Stream;

import cn.lyf.myblog.dataFlow.Flow;
import cn.lyf.myblog.mybatis.entity.*;
import cn.lyf.myblog.mybatis.mappers.*;

@Service
public class CommentService {
    final Flow<ObjectNode> flow = new Flow<>();

    @Autowired
    CommentsMapper commentsMapper;
    @Autowired
    UserInfo2Mapper userInfo2Mapper;

    public CommentService() {
        flow.setHandler("getUserInfo2", this::getUserInfo2);
        flow.setHandler("getReplys", this::getReplys);
        flow.setHandler("getReplyUser", this::getReplyUser);
    }

    public ObjectNode getCommentsInfo(ObjectNode json) throws Exception {
        Integer bid = getInteger(json, "/blogId");
        Integer pageNo = getInteger(json, "/pageNo");
        Integer limit = getInteger(json, "/pageSize");
        List<Comments> list = commentsMapper.selectCommentsByBid(bid, limit, pageNo * limit);
        ObjectNode res = mapper.createObjectNode();
        res.put("success", true);
        res.put("message", "获取评论成功");
        res.put("code", 200);
        ObjectNode result = mapper.createObjectNode();
        result.put("pageNo", pageNo);
        result.put("total", list.size());
        Stream<ObjectNode> ss = list.stream().map(e -> mapper.valueToTree(e));
        List<ObjectNode> l = flow.stream().pipe(ss, "getUserInfo2").pipe("getReplys").pipe("getReplyUser").collect();
        result.putPOJO("data", l);
        res.set("result", result);
        return res;
    }

    public ObjectNode getUserInfo2(ObjectNode json) {
        Integer uid = getInteger(json, "/uid");
        if (uid == null)
            return json;
        json.remove("uid");
        json.putPOJO("user", userInfo2Mapper.selectUserInfo2ById(uid));
        return json;
    }

    public ObjectNode getReplys(ObjectNode json) {
        Integer pcid = getInteger(json, "/pcid");
        System.out.println(json);
        json.remove("pcid");
        if (pcid != null) {
            JsonNode node=mapper.convertValue(commentsMapper.selectCommentsByCid(pcid), JsonNode.class);
            json.set("reply",node);
        }
        return json;
    }

    public ObjectNode getReplyUser(ObjectNode json) {
        JsonNode reply = json.get("reply");
        if (reply == null)
            return json;
        // 设计缺陷，管道没有定位功能,有耦合
        ObjectNode res = getUserInfo2(reply.deepCopy());
        json.set("reply", res);
        return json;
    }
}
